package main

import (
	"os"
	"fmt"
	"strconv"
)

const Usage = `
Usage:
	./blockchain createBlockChain ADDRESS "创建区块链"
	./blockchain addBlock DATA   "添加数据到区块链"
	./blockchain printChain "打印区块链"
	./blockchain printTx "打印交易"
	./blockchian getBalance ADDRESS "获取指定地址余额"
	./blockchian send FROM TO AMOUNT MINER DATA  "转账"
	./blockchian createWallet "创建钱包地址"
	./blockchian listAllAddress "打印钱包中的所有地址"
`

//定义一个CLI，里面包含BlockChain，所有细节工作交给bc，命令的解析工作交给CLI
type CLI struct {
	//bc *BlockChain
}

func checkArgs(count int) {
	if len(os.Args) != count {
		fmt.Println("参数无效!")
		os.Exit(1)
	}
}

//定义一个run函数，负责接收命令行的数据，然后根据命令进行解析，并完成最终的调用
func (cli *CLI) Run() {
	args := os.Args

	if len(args) < 2 {
		fmt.Println(Usage)
		os.Exit(1)
	}

	cmd := args[1]

	switch cmd {

	case "createBlockChain":
		fmt.Printf("创建区块链命令被调用!\n")
		checkArgs(3)
		address := args[2]
		cli.CreateBlockChain(address)

	case "printChain":
		fmt.Printf("打印区块命令被调用\n")
		checkArgs(2)
		cli.PrintChain()

	case "printTx":
		fmt.Printf("打印交易命令被调用\n")
		checkArgs(2)
		cli.PrintTx()

	case "getBalance":
		fmt.Printf("获取余额命令被调用\n")
		checkArgs(3)
		address := args[2]
		cli.GetBalance(address)

	case "send":
		fmt.Printf("转账send命令被调用\n")
		checkArgs(7)

		from := args[2]
		to := args[3]
		amount, _ := strconv.ParseFloat(args[4], 64) //string
		miner := args[5]
		data := args[6]
		cli.Send(from, to, amount, miner, data)

	case "createWallet":
		fmt.Printf("createWallet命令被调用\n")
		checkArgs(2)

		cli.CreateWallet()
	case "listAllAddress":
		fmt.Printf("listAllAddress命令被调用\n")
		checkArgs(2)
		cli.ListAllAddress()

	default:
		fmt.Printf("无效的命令，请检查!\n")
	}
}
